<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学校" prop="schoolId">
        <el-select v-model="queryParams.schoolId" placeholder="请选择学校">
          <el-option v-for="item in schoolList" :key="item.userId" :value="item.userId" :label="item.userName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择类型" clearable>
          <el-option label="老师" value="TEACHER" />
          <el-option label="学生" value="STUDENT" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓氏" prop="lastName">
        <el-input
          v-model="queryParams.lastName"
          placeholder="请输入姓氏"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名字" prop="firstName">
        <el-input
          v-model="queryParams.firstName"
          placeholder="请输入名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['account:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchAdd"
          v-hasPermi="['account:add']"
        >批量
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['account:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['account:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['account:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="序号" align="left" width="100" prop="id"/>
      <el-table-column label="学校" align="left" prop="school"/>
      <el-table-column label="类型" align="left" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.userType === 'TEACHER' ? '老师' : '学生' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓氏" align="c" prop="lastName"/>
      <el-table-column label="名字" align="left" prop="firstName"/>
      <el-table-column label="邮箱" align="left" width="400" prop="email"/>
      <el-table-column label="算力" align="left" width="50" prop="usageCount"/>
      <el-table-column label="过期时间" align="center" prop="expirationDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['account:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleResetPassword(scope.row)"
            v-hasPermi="['account:edit']"
          >重置
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['account:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改账号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="学校" prop="school" :rules="[{required: true, message: '学校不能为空'}]">
          <span v-if="form.id != null">{{ form.school }}</span>
          <el-select v-model="form.school" v-else placeholder="请选择学校" @change="handleSchoolChange">
            <el-option v-for="item in schoolList" :key="item.userId" :value="item.userId" :label="item.userName"/>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="userType" :rules="[{required: true, message: '类型不能为空'}]">
          <span v-if="form.id != null">{{ form.userType === 'TEACHER' ? '老师' : '学生' }}</span>
          <el-select v-model="form.userType" v-else placeholder="请选择类型" clearable>
            <!--<el-option label="老师" value="TEACHER" /> -->
            <el-option label="学生" value="STUDENT" />
          </el-select>
        </el-form-item>
        <el-form-item label="老师编号" prop="teacherCode" v-if="form.userType == 'STUDENT'" :rules="[{required: true, message: '老师编号不能为空'}]">
          <el-input v-model="form.teacherCode" placeholder="请输入老师编号"/>
        </el-form-item>
        <el-form-item label="姓氏" prop="lastName" v-if="!batchAdd" :rules="[{required: true, message: '姓氏不能为空'}]">
          <el-input v-model="form.lastName" placeholder="请输入姓氏"/>
        </el-form-item>
        <el-form-item label="名字" prop="firstName" v-if="!batchAdd" :rules="[{required: true, message: '名字不能为空'}]">
          <el-input v-model="form.firstName" placeholder="请输入名字"/>
        </el-form-item>
        <el-form-item :label="batchAdd ? '账户前缀' : '账户'" prop="username" v-if="form.id == null" :rules="[{required: true, message: '账户不能为空'}]">
          <el-input v-model="form.username" placeholder="请输入账户"/>
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="[{required: true, message: '密码不能为空'}, { min: 8, message: '密码长度不能小于8位', trigger: 'blur' }]">
          <span v-if="form.id != null">{{ form.password }}</span>
          <el-input type="password" v-else v-model="form.password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" v-if="!batchAdd" :rules="[{required: true, message: '邮箱不能为空'}]">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="算力" prop="usageCount" :rules="[{required: true, message: '算力不能为空'}]">
          <span v-if="form.id != null">{{ form.usageCount }}</span>
          <el-input v-else v-model="form.usageCount" placeholder="请输入算力"/>
        </el-form-item>
        <el-form-item label="数量" prop="count" v-if="batchAdd" :rules="[{required: true, message: '数量不能为空'}]">
          <el-input v-model="form.count" placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item label="过期时间" prop="expirationDate" :rules="[{required: true, message: '过期时间不能为空'}]">
          <span v-if="form.id != null">{{ formatDate(form.expirationDate) }}</span>
          <el-date-picker v-else v-model="form.expirationDate" type="date" placeholder="请选择过期时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="resetPwdShow" width="500px" append-to-body>
      <el-form ref="resetPwdForm" :model="resetPwdForm" label-width="80px">
        <el-form-item label="密码" prop="newPassword" :rules="[{required: true, message: '密码不能为空'}, { min: 8, message: '密码长度不能小于8位', trigger: 'blur' }]">
          <el-input v-model="resetPwdForm.newPassword" placeholder="请输入最新密码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitRestPassword">确 定</el-button>
        <el-button @click="resetPwdShow=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addAccount, delAccount, getAccount, listAccount, resetPassword, updateAccount} from "@/api/account/account"
import {listAllChannelUser} from "@/api/system/channel";
import {formatDate} from "@/utils";

export default {
  name: "Account",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 账号表格数据
      accountList: [],
      agentList: [],
      schoolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      batchAdd: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userType: null,
        agentId: null,
        agent: null,
        schoolId: null,
        school: null,
        firstName: null,
        lastName: null,
        username: null,
        password: null,
        email: null,
        usageCount: null,
        status: null,
        expirationDate: null,
        ids: [],
      },
      // 表单参数
      form: {},
      resetPwdShow: false,
      resetPwdForm: {
        userId: '',
        newPassword: ''
      },
    }
  },
  created() {
    this.getList()
  },
  watch: {
  },
  methods: {
    formatDate,
    /** 查询账号列表 */
    getList() {
      this.loading = true
      listAccount(this.queryParams).then(response => {
        this.accountList = response.rows
        this.total = response.total
        this.loading = false
      })
      this.getAllChannelList()
    },
    getAllChannelList() {
      listAllChannelUser().then(res => {
        if (res.code === 200) {
          const data = res.data || []
          this.agentList = data.filter(item => ['10', '11', '12'].includes(item.userType)) || []
          this.schoolList = data.filter(item => item.userType === '20') || []
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        schoolId: null,
        school: null,
        userType: null,
        teacherCode: null,
        lastName: null,
        firstName: null,
        username: null,
        password: null,
        email: null,
        usageCount: null,
        count: null,
        expirationDate: null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSchoolChange(schoolId) {
      if (schoolId && this.schoolList.length > 0) {
        const selectedSchool = this.schoolList.find(item => item.userId === schoolId);
        if (selectedSchool) {
          this.form.school = selectedSchool.userName;
        }
      } else {
        this.form.school = '';
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.batchAdd = false
      this.title = "添加账号"
    },
    /** 批量新增按钮操作 */
    handleBatchAdd() {
      this.reset()
      this.open = true
      this.batchAdd = true
      this.title = "批量添加账号"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.batchAdd = false
      const id = row.id || this.ids
      getAccount(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改账号"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAccount(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAccount(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除账号编号为"' + ids + '"的数据项？').then(function () {
        return delAccount(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.ids = this.ids;
      this.download('account/export', {
        ...this.queryParams
      }, `account_${new Date().getTime()}.xlsx`)
    },
    handleResetPassword(row) {
      this.resetPwdForm = {
        userId: row.id,
        newPassword: ''
      }
      this.resetPwdShow = true
    },
    onSubmitRestPassword() {
      this.$refs["resetPwdForm"].validate(valid => {
        if (valid) {
          resetPassword({
            userId: this.resetPwdForm.userId,
            newPassword: this.resetPwdForm.newPassword
          }).then(response => {
            this.$modal.msgSuccess("重置密码成功")
            this.resetPwdShow = false
          })
        }
      })
    },
  }
}
</script>
